<template>
  <div class="search-result-list__container">
    <!-- 搜索结果页-头部导航 -->
    <div class="search-result-container">
      <!-- 点击实现后退效果 -->
      <van-nav-bar
        title="搜索结果"
        left-arrow
        @click-left="$router.go(-1)"
        fixed
      />
    </div>
    <div class="search-list__content">
      <!-- 这里需要循环生成 ArticleItem 组件 -->
      <van-list
        v-model="loading"
        :finished="done"
        :immediate-check="false"
        offset="50"
        @load="pullUpLoadMoreFn">
        <ArticleItem
          v-for="item in resultList"
          :key="item.art_id"
          :item="item"
          :isShowCross="false"
        />
      </van-list>
    </div>
  </div>
</template>

<script>
import { getSearchResultListAPI } from '@/api/search'
// 页码，默认值 是 1
let page = 1
export default {
  name: 'SearchResultList',
  data () {
    return {
      resultList: [], // 搜索结果列表
      loading: false,
      done: false
    }
  },
  async created () {
    this.getSearchResultList()
  },
  /*
    destroyed:
    deactivated:
  */
  computed: {
    txt () {
      return this.$route.params.keyword
    }
  },
  methods: {
    // 获取搜索结果列表
    async getSearchResultList () {
      // 1. 发请求
      const resp = await getSearchResultListAPI({
        keyword: this.txt,
        page: page++
      })
      const { results } = resp.data
      // 全部加载完毕
      if (results.length < 10) {
        this.done = true
        return
      }
      // 2. 合并数据
      this.resultList = [...this.resultList, ...results]

      // 可以继续加载下一页
      this.loading = false
    },
    // 上拉加载更多
    pullUpLoadMoreFn () {
      if (this.resultList.length > 0) {
        this.getSearchResultList()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
